﻿using CIS.Web.Common;
using CIS.Web.Models;
using CIS.Web.Properties;
using System;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace CIS.Web.Controllers
{
	[RoutePrefix("ConferenceNotice")]
	public class ConferenceNoticeController : BaseDbController
	{
		[Route("Index/{ConferenceId}")]
		public async Task<ActionResult> Index(string conferenceId)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", conferenceId);

			var conferenceMaster = await DbContext.ConferenceMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.Status == ConstValues.Status.正常 &&
						x.ID == conferenceId);

			ViewBag.ConferenceName = conferenceMaster.ConferenceName;
			ViewBag.ConferenceId = conferenceId;
			ViewBag.ControllerName = Resources.ConferenceNotice;
			ViewBag.Language = conferenceMaster.IsInternational ? ConstValues.Language.En : ConstValues.Language.Cn;

			var model = new ConferenceMasterModel();
			model.Id = conferenceId;
			LoginUser.ConferenceFunctionIdList = Utility.GetConferenceFunctionIdList(conferenceId);
			return View(model);
		}

		public async Task<JsonCamelCaseResult> GetEditData(string id)
		{
			var data = await DbContext.ConferenceNoticeMaster.AsNoTracking().FirstOrDefaultAsync(x => x.ID == id);

			if (data == null)
			{
				string errorMessage = Resources.MsgRecordNotExist;
				return JsonCamelCase(Utility.CreateFailJsonResult(errorMessage),
						JsonRequestBehavior.AllowGet);
			}

			var result = new
			{
				ConferenceName = data.ConferenceName,
				ConferenceNickName = data.ConferenceNickName,
				OperateTime = data.OperateTime,
				OperateLocation = data.OperateLocation,
				ConferenceAddress = data.ConferenceAddress,
				Sponsor = data.Sponsor,
				HomePageUrl = data.HomePageUrl,
				Supporter = data.Supporter,
				Contact = data.Contact,
				ContactPhone = data.ContactPhone,
				ContactMail = data.ContactMail,
				PicForStamp = Path.GetFileName(data.PicForStamp),
				CustomDefinition = data.CustomDefinition == null ? string.Empty : data.CustomDefinition,
				HasAttachment = data.HasAttachment,
			};

			return JsonCamelCase(Utility.CreateSuccessJsonResult(ConstValues.AjaxSuccessResult, result),
					JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		[ValidateInput(false)]
		[Route("Edit/{ConferenceId}")]
		public async Task<JsonResult> Edit(ConferenceMasterModel model, FormCollection formCollection)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.Id);

			var result = await DbContext.ConferenceNoticeMaster.FirstOrDefaultAsync(x => x.ID == model.Id);

			if (result == null)
			{
				string errorMessage = Resources.MsgRecordNotExist;
				return JsonCamelCase(Utility.CreateFailJsonResult(errorMessage),
						JsonRequestBehavior.AllowGet);
			}

			result.OperateTime = model.OperateTime?.Trim();
			result.OperateLocation = model.OperateLocation?.Trim();
			result.ConferenceAddress = model.ConferenceAddress?.Trim();
			result.Sponsor = model.Sponsor?.Trim();
			result.HomePageUrl = model.HomePageUrl?.Trim();
			result.Supporter = model.Supporter;
			result.Contact = model.Contact?.Trim();
			result.ContactPhone = model.ContactPhone?.Trim();
			result.ContactMail = model.ContactMail?.Trim();

			string nickName = result.ConferenceNickName;
			string folder = Path.Combine(ConstValues.ConferenceImg, nickName);
			string pfolder = Path.Combine(Server.MapPath(ConstValues.ConferenceImg), nickName);

			if (model.PicForStampFile != null)
			{
				if (model.PicForStampFile.ContentLength > ConstValues.PicMaxLength)
				{
					string errorMessage = Resources.MsgPicOverflowError;
					return JsonCamelCase(Utility.CreateFailJsonResult(errorMessage),
						JsonRequestBehavior.AllowGet);
				}

				string fileName = nickName + ConstValues.strHyphen +
						Path.GetExtension(model.PicForStampFile.FileName).Replace(".", "").ToUpper() + ConstValues.strHyphen +
						DateTime.Now.ToString("yyyy") + ConstValues.strHyphen +
						Utility.GetRandom() + Path.GetExtension(model.PicForStampFile.FileName);
				model.PicForStampFilePath = Path.Combine(folder, fileName);
				var saveFileTask = Task.Run(() =>
				{
					string pFullPath = Path.Combine(pfolder, fileName);
					if (!Directory.Exists(pfolder))
					{
						Directory.CreateDirectory(pfolder);
					}
					model.PicForStampFile.SaveAs(pFullPath);
				});
				Task.WaitAll(saveFileTask);
				result.PicForStamp = model.PicForStampFilePath;
			}
			else if (string.IsNullOrEmpty(model.PicForStampFilePath))
			{
				result.PicForStamp = string.Empty;
			}

			result.CustomDefinition = model.CustomDefinition == null ? string.Empty : model.CustomDefinition.Trim();
			result.HasAttachment = formCollection.AllKeys.FirstOrDefault(x => x == "HasAttachment") == null ? false : true;

			result.Updater = LoginUser.UserName;
			result.UpdateIP = LoginUser.IP;
			result.UpdateDate = DateTime.Now;
			await DbContext.SaveChangesAsync();

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
					JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[ValidateInput(false)]
		[Route("Preview/{ConferenceId}")]
		public async Task<JsonResult> Preview(ConferenceMasterModel model)
		{
			var conferenceMaster = await DbContext.ConferenceMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.Status == ConstValues.Status.正常 &&
						x.ID == model.Id);

			var conferenceNotice = await DbContext.ConferenceNoticeMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ID == model.Id);

			var dateTimeNow = DateTime.Now.ToString("yyyyMMddHHmmss");

			//图章img
			var stampFile = string.Empty;
			if (!string.IsNullOrEmpty(conferenceNotice.PicForStamp))
			{
				var fileName = Path.GetFileName(conferenceNotice.PicForStamp);
				var pfolder = Path.Combine(Server.MapPath(ConstValues.ConferenceImg), conferenceNotice.ConferenceNickName);
				var pFullPath = Path.Combine(pfolder, fileName);

				if (System.IO.File.Exists(pFullPath))
				{
					var stampFolder = Server.MapPath(Path.Combine(ConstValues.ConferenceImg, conferenceNotice.ConferenceNickName));
					var stampFileName = Path.GetFileName(conferenceNotice.PicForStamp);
					stampFile = Path.Combine(stampFolder, stampFileName);
				}
			}

			var pdfFolder = Server.MapPath(Path.Combine(ConstValues.PdfPreview, conferenceNotice.ConferenceNickName));
			var pdfFile = pdfFolder + ConstValues.InvitationLetterPdfPreview + "_" + dateTimeNow + ".pdf";

			Utility.CreatePdf(conferenceMaster, conferenceNotice, stampFile, pdfFile, LoginUser.UserName);

			var filePhyName = conferenceNotice.ConferenceNickName + ConstValues.InvitationLetterPdfPreview + "_" + dateTimeNow + ".pdf";
			var pdfFilePath = Path.Combine(ConstValues.PdfPreview, conferenceNotice.ConferenceNickName);
			var pdfFilePhyPath = pdfFilePath + ConstValues.InvitationLetterPdfPreview + "_" + dateTimeNow + ".pdf";

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit, pdfFilePhyPath),
					JsonRequestBehavior.AllowGet);
		}
	}
}